#!/usr/bin/env bash
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -ex

function install_lcov
{
    LCOV_TAR_GZ_LINK=$1
    LCOV_VERSION=$2

    apt install -y perl libdatetime-perl libjson-perl libperlio-utf8-strict-perl libcapture-tiny-perl libtimedate-perl

    curl --retry 5 --retry-delay 10 -L "${LCOV_TAR_GZ_LINK}" -o /tmp/lcov.tar.gz
    tar -xf /tmp/lcov.tar.gz --directory /tmp/
    cd /tmp/lcov-${LCOV_VERSION}
    make install || echo "Make install failed"
    llvm_cov=$(which llvm-cov 2>/dev/null ||
               find /usr/bin /usr/local/bin -name 'llvm-cov*' -print -quit 2>/dev/null ||
               find /usr/bin /usr/local/bin -name 'llvm-cov*' -type f -print -quit 2>/dev/null || true)
    if [[ -n "${llvm_cov}" ]]; then
        ln -sf "${llvm_cov}" /usr/bin/llvm-cov-gcov || echo "WARNING: Failed to create llvm-cov-gcov symlink"
    else
        echo "WARNING: llvm-cov not found, tried multiple naming variants"
    fi

    sed -e 's/branch_coverage = 0/branch_coverage = 1/' \
        -e 's/#ignore_errors = empty,mismatch/ignore_errors = empty,utility,range,inconsistent,source,format,category/' \
        /tmp/lcov-${LCOV_VERSION}/lcovrc >  ~/.lcovrc
}
